package com.xxx.modules.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageStreamUtil {

    public static byte[] image2byte(String path){

        // 设置参数
        InputStream in = null;
        ByteArrayOutputStream byteArrOps = null;
        int length;
        byte[] buffer = new byte[1024 * 5];
        byte[] data = null;

        try {
            URL url = new URL(path);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(1000 * 60);
            if (urlConnection.getResponseCode() == 200) {
                in = urlConnection.getInputStream();
                byteArrOps = new ByteArrayOutputStream();
                while ((length = in.read(buffer)) != -1) {
                    byteArrOps.write(buffer, 0, length);
                }
                byteArrOps.flush();
                data = byteArrOps.toByteArray();
                // 下载大小: data.length
            }
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (byteArrOps != null) {
                    byteArrOps.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }

}
